using System;
using System.Linq;
using System.Xml.Linq;

namespace NetQueryLib
{
	public sealed class NodeWalker
	{
		private readonly XElement _startingElement;

		public NodeWalker(XElement startingElement)
		{
			_startingElement = startingElement;
			CurrentElement = startingElement;
		}

		public XElement CurrentElement { get; private set; }

		public bool MoveNext()
		{
			if(CurrentElement == null)
				return false;

			var nextElement = CurrentElement.Elements().FirstOrDefault() ?? CurrentElement.ElementsAfterSelf().FirstOrDefault();

			var parent = CurrentElement.Parent;
			while (nextElement == null && parent != null && parent != _startingElement)
			{
				nextElement = parent.ElementsAfterSelf().FirstOrDefault();
				parent = parent.Parent;
			}

			CurrentElement = nextElement;

			return CurrentElement != null;
		}
	}
}